package tests;





import java.io.*;

import index.ColumnIndexScan;
import iterator.*;

import iterator.CondExpr;

import iterator.FldSpec;

import iterator.RelSpec;

import java.io.*;

import java.util.*;
import java.lang.*;
import heap.*;
import bufmgr.*;
import diskmgr.*;
import global.*;
import chainexception.*;

import columnar.*;

public class DeleteQueryTest  implements GlobalConst {

	/*
	 * constructor for all parameters - datafilename , coulmnDBname, columnar
	 * filename , numcolumns
	 */
	public String datafilename, cdbname, filename;
	public int numcolumns;
	public TID[] tidArr;
	ColumnarFile _cf;
	int[] colnosg;
	int[] attrtypesg;
	public BitSet deletedList = new BitSet();
	public int deleteListIndex;
	public int bitarrSize = 0;

	public DeleteQueryTest() {
	}

	

//	public void runTest1(String cdbname, String Colfilename, String cname,
//			String[] targetcolname, String operator, String value,
//			String accesstype) throws IOException
//
//	{
//		try
//		{
//			/*for(int a=0; a<10000;a++)
//			{
//			this.deletedList.set(this.deleteListIndex++, true);
//			this.bitarrSize = this.deletedList.length();
//			//System.out.println(this.deletedList.length());
//		
//			// byte[] bArr = convertToByteArray(deletedList, 1);
//			// BitSet bSet = fromByteArray(bArr);
//			
//			}*/
//			String dbpath = "/tmp/" + cdbname;
//	String record;
//
//	int numbuf, targetnum, nocol;
//	Scanner sc = new Scanner(System.in);
//	SystemDefs sysdef = new SystemDefs(dbpath, 0, 1000, "Clock");
//		PCounter.initialize();
//		this.filename = Colfilename;
//		int i = 0, z = 0;
//		
//		BufferedReader br = new BufferedReader(new FileReader("/tmp/"+Colfilename+".hdr"));
//
//		while ((record = br.readLine()) != null) {
//			z++;
//		}
//		this.numcolumns = z;
//		int[] colnos = new int[this.numcolumns];
//		int[] attrtypes = new int[this.numcolumns];
//		// all colnames, colnumbers and attr by parsing the name.hdr
//		String[] colnames = new String[this.numcolumns];
//		// int[] colnos = new int[this.numcolumns];
//		// int[] attrtypes = new int[this.numcolumns];
//		// constraint colname,attr,number
//		int condn_columnno = -1, condn_attrType = -1;
//		String condn_columnname = " ";
//		// target column number and attr
//		int[] final_colnums = new int[targetcolname.length];
//		int[] final_attr = new int[targetcolname.length];
//		String[] targetarray = new String[this.numcolumns];
//		// read from name.hdr
//		BufferedReader br4 = new BufferedReader(new FileReader("/tmp/"+Colfilename+".hdr"));
//
//		while ((record = br4.readLine()) != null) {
//
//			StringTokenizer st4 = new StringTokenizer(record, "\t");
//
//			while (st4.hasMoreTokens()) {
//				StringTokenizer st5 = new StringTokenizer(st4.nextToken(), " ");
//				String colName = st5.nextToken().trim();
//				colnames[i] = colName;
//				int colNum = Integer.parseInt(st5.nextToken().trim());
//				colnos[i] = colNum;
//				int attrType = Integer.parseInt(st5.nextToken().trim());
//				attrtypes[i] = attrType;
//
//				if (colName.equals(cname)) {
//					condn_columnno = colNum;
//					condn_attrType = attrType;
//					condn_columnname = colName;
//
//				}
//
//			}
//
//			i++;
//
//		}
//		
//	/*	RID rid1 = new RID();
//		Heapfile hpf = new Heapfile(this.filename+(condn_columnno-1));
//		Scan scan1 = new Scan(hpf);
//		for(i=0;i<hpf.getRecCnt();i++)
//		{
//			Tuple t1 = new Tuple();
//			AttrType[] at = new AttrType[1];
//			short[] tsize1 = new short[1];
//			if(condn_attrType == 0)
//			{
//			at[0] = new AttrType(AttrType.attrString);
//			tsize1[0] = strlen;
//			}
//			else
//			 at[0] = new AttrType(AttrType.attrInteger);
//			
//
//			t1.setHdr((short) 1, at, tsize1);
//			// t.getStrFld(1,data[i]);
//
//			Tuple tup1 = new Tuple(t1.size());
//			tup1.setHdr((short) 1, at, tsize1);
//			tup1 = scan1.getNext(rid1);
//			t1.tupleCopy(tup1);
//			
//			if(condn_attrType == 0)
//			{
//				System.out.println(t1.getStrFld(1));
//			}
//			else
//			{
//				System.out.println(t1.getIntFld(1));
//			}
//				
//		}
//*/		
//		RID rid = new RID();
//		Heapfile hf = new Heapfile(this.filename+(condn_columnno-1));
//		Scan scan = new Scan(hf);
//		int scanpos = -1;
//		for(i=0;i<hf.getRecCnt();i++)
//		{
//			
//				Tuple t1 = new Tuple();
//				AttrType[] at = new AttrType[1];
//				short[] tsize1 = new short[1];
//				if(condn_attrType == 0)
//				{
//				at[0] = new AttrType(AttrType.attrString);
//				tsize1[0] = strlen;
//				}
//				else
//				 at[0] = new AttrType(AttrType.attrInteger);
//				
//
//				t1.setHdr((short) 1, at, tsize1);
//				// t.getStrFld(1,data[i]);
//
//				Tuple tup1 = new Tuple(t1.size());
//				tup1.setHdr((short) 1, at, tsize1);
//				tup1 = scan.getNext(rid);
//				t1.tupleCopy(tup1);
//				
//				if(condn_attrType == 0)
//				{
//					
//					if(t1.getStrFld(1).equalsIgnoreCase(value))
//					{
//						System.out.println(t1.getStrFld(1));
//						for(int b=0; b<this.numcolumns;b++)
//						{
//							 RID rtemp = new RID();
//							/*  boolean status;
//							Heapfile hf1 = new Heapfile(this.filename+b);
//							status= hf1._findPositionPage(rtemp, i);
//							tup1 = hf1.getRecord(rtemp);
//				  			t1.tupleCopy(tup1);
//				  			System.out.println(t1.getStrFld(1));
//											  			
//							 status = hf1.deleteRecord(rtemp);*/
//							int pos = 0;
//							Heapfile hf1 = new Heapfile(this.filename+b);
//							Scan sc1= new Scan(hf1);
//							for(int c=0; c<hf1.getRecCnt();c++)
//							{
//								Tuple tp = sc1.getNext(rtemp);
//								if((c-1) == i)
//									hf1.deleteRecord(rtemp);
//							}
//							
//						}
//						
//					}
//				}
//				else
//				{
//					System.out.println("value got"+t1.getIntFld(1));
//					
//					if(t1.getIntFld(1)== Integer.parseInt(value))
//					{
//						System.out.println("value equal:"+t1.getIntFld(1));
//						hf.deleteRecord(rid);
//						for(int b=0; b<this.numcolumns;b++)
//						{
//							if(b != (condn_columnno-1))
//							{
//							RID rtemp = new RID();
//							Heapfile hf1 = new Heapfile(this.filename+b);
//							Scan sc1= new Scan(hf1);
//					//		System.out.println("heap count:"+hf1.getRecCnt());
//							for(int c=0; c<hf1.getRecCnt();c++)
//							{
//								 sc1.getNext(rtemp);
//								if((c) == i)
//								{
//									System.out.println("position:"+c+",i:"+i);
//									hf1.deleteRecord(rtemp);
//									break;
//								}
//							}
//							 
//							}	/*  boolean status;
//								Heapfile hf1 = new Heapfile(this.filename+b);
//								status= hf1._findPositionPage(rtemp, i);
//								tup1 = hf1.getRecord(rtemp);
//					  			t1.tupleCopy(tup1);
//					  			System.out.println(t1.getStrFld(1));
//												  			
//								 status = hf1.deleteRecord(rtemp);*/
//							
//							
//						/*	int position=-1;
//								Heapfile hf1 = new Heapfile(this.filename+b);
//								Scan sc1= new Scan(hf1);
//								
//								RID rtemp = new RID();
//								RID rtemp1 = new RID();
//								do {
//									rtemp1 = rtemp;
//									sc1.getNext(rtemp);
//									position++;
//								} while (position != i);
//								System.out.println("position:"+position+",i:"+i);
//								hf1.deleteRecord(rtemp1); */
//							 
//						}
//					}
//				}
//			
//			
//			// operato == " ="
//		}// for loop for each of the target column  value
//		
//		
//		
//		
//		}
//		catch (Exception e) {
//			System.out.println(e.getMessage());
//		} finally {
//			try {
//				// IntegerValue vc = new IntegerValue(new Integer(1));
//				// cf.createBitMapIndex(2, (ValueClass)vc);
//				// for(i=0;i<this.tidArr.length;i++)
//				// cf.getTuple(this.tidArr[i]);
//				// cf.markTupleDeleted(tid);
//				// cf.purgeAllDeletedTuples();
//				SystemDefs.JavabaseBM.unpinAllPages();
//				SystemDefs.JavabaseBM.flushAllPages();
//				System.out.println("Number of Pages Read: " + PCounter.rcounter);
//				System.out.println("Number of Pages Written: "
//						+ PCounter.wcounter);
//			} catch (Exception e) {
//			}
//		}
//
//
//	} 

	public void runTest1(String cdbname, String Colfilename, String cname,
			String[] targetcolname, String operator, String value,
			String accesstype, int numbuf) throws IOException

	{
		try
		{
			/*for(int a=0; a<10000;a++)
			{
			this.deletedList.set(this.deleteListIndex++, true);
			this.bitarrSize = this.deletedList.length();
			//System.out.println(this.deletedList.length());
		
			// byte[] bArr = convertToByteArray(deletedList, 1);
			// BitSet bSet = fromByteArray(bArr);
			
			}*/
			String dbpath = "/tmp/" + cdbname;
	String record;

	int  targetnum, nocol;
	Scanner sc = new Scanner(System.in);
	SystemDefs sysdef = new SystemDefs(dbpath, 0, numbuf, "Clock");
		PCounter.initialize();
		this.filename = Colfilename;
		int i = 0, z = 0;
		
		BufferedReader br = new BufferedReader(new FileReader("/tmp/"+Colfilename+".hdr"));

		while ((record = br.readLine()) != null) {
			z++;
		}
		this.numcolumns = z;
		int[] colnos = new int[this.numcolumns];
		int[] attrtypes = new int[this.numcolumns];
		// all colnames, colnumbers and attr by parsing the name.hdr
		String[] colnames = new String[this.numcolumns];
		// int[] colnos = new int[this.numcolumns];
		// int[] attrtypes = new int[this.numcolumns];
		// constraint colname,attr,number
		int condn_columnno = -1, condn_attrType = -1;
		String condn_columnname = " ";
		// target column number and attr
		int[] final_colnums = new int[targetcolname.length];
		int[] final_attr = new int[targetcolname.length];
		String[] targetarray = new String[this.numcolumns];
		// read from name.hdr
		BufferedReader br4 = new BufferedReader(new FileReader("/tmp/"+Colfilename+".hdr"));

		while ((record = br4.readLine()) != null) {

			StringTokenizer st4 = new StringTokenizer(record, "\t");

			while (st4.hasMoreTokens()) {
				StringTokenizer st5 = new StringTokenizer(st4.nextToken(), " ");
				String colName = st5.nextToken().trim();
				colnames[i] = colName;
				int colNum = Integer.parseInt(st5.nextToken().trim());
				colnos[i] = colNum;
				int attrType = Integer.parseInt(st5.nextToken().trim());
				attrtypes[i] = attrType;

				if (colName.equals(cname)) {
					condn_columnno = colNum;
					condn_attrType = attrType;
					condn_columnname = colName;

				}

			}

			i++;

		}
		if(condn_columnname.equalsIgnoreCase(" "))
		{
			System.out.println("Given column didnt match");
			
		}
		else
		{
		
	/*	RID rid1 = new RID();
		Heapfile hpf = new Heapfile(this.filename+(condn_columnno-1));
		Scan scan1 = new Scan(hpf);
		for(i=0;i<hpf.getRecCnt();i++)
		{
			Tuple t1 = new Tuple();
			AttrType[] at = new AttrType[1];
			short[] tsize1 = new short[1];
			if(condn_attrType == 0)
			{
			at[0] = new AttrType(AttrType.attrString);
			tsize1[0] = strlen;
			}
			else
			 at[0] = new AttrType(AttrType.attrInteger);
			

			t1.setHdr((short) 1, at, tsize1);
			// t.getStrFld(1,data[i]);

			Tuple tup1 = new Tuple(t1.size());
			tup1.setHdr((short) 1, at, tsize1);
			tup1 = scan1.getNext(rid1);
			t1.tupleCopy(tup1);
			
			if(condn_attrType == 0)
			{
				System.out.println(t1.getStrFld(1));
			}
			else
			{
				System.out.println(t1.getIntFld(1));
			}
				
		}
*/		
		RID rid = new RID();
		Heapfile hf[] = new Heapfile[this.numcolumns];
		Scan scan[] = new Scan[this.numcolumns];
		for(int m =0 ; m<this.numcolumns ; m++)
		{
			hf[m] = new Heapfile(this.filename+ m);
			System.out.println(this.filename+ m);
		}
		for(int m =0 ; m<this.numcolumns ; m++)
		{
			scan[m] = new Scan(hf[m]);
			
		}
		boolean matchfound = false;
		while(scan[condn_columnno-1].getNext(rid)!=null)
		{
			
			boolean recordDeleted= false;
			
			Tuple t1 = new Tuple();
			AttrType[] at = new AttrType[1];
			short[] tsize1 = new short[1];
			if(condn_attrType == 0)
			{
			at[0] = new AttrType(AttrType.attrString);
			tsize1[0] = strlen;
			}
			else
			 at[0] = new AttrType(AttrType.attrInteger);
			

			t1.setHdr((short) 1, at, tsize1);
			// t.getStrFld(1,data[i]);

			Tuple tup1 = new Tuple(t1.size());
			tup1.setHdr((short) 1, at, tsize1);
			tup1 = hf[condn_columnno-1].getRecord(rid);
			t1.tupleCopy(tup1);
			if(condn_attrType == 0)
			{
				System.out.println(t1.getStrFld( 1));
				if(operator.equalsIgnoreCase("="))
				{
				if(t1.getStrFld( 1).equalsIgnoreCase(value))
				{
					if(matchfound == false)
						matchfound= true;
					hf[condn_columnno-1].deleteRecord(rid);
					recordDeleted = true;
				}
				}
				if(operator.equalsIgnoreCase(">"))
				{
					int result = t1.getStrFld( 1).compareToIgnoreCase(value);
				if(result>0)
				{
					if(matchfound == false)
						matchfound= true;
					hf[condn_columnno-1].deleteRecord(rid);
					recordDeleted = true;
				}
				}
				if(operator.equalsIgnoreCase("<"))
				{
					int result = t1.getStrFld( 1).compareToIgnoreCase(value);
				if(result<0)
				{
					if(matchfound == false)
						matchfound= true;
					hf[condn_columnno-1].deleteRecord(rid);
					recordDeleted = true;
				}
				}
			}
			else
			{
			System.out.println(t1.getIntFld( 1));
			if(operator.equalsIgnoreCase("="))
			{
			if(t1.getIntFld( 1)== Integer.parseInt(value))
			{
				if(matchfound == false)
					matchfound= true;
				hf[condn_columnno-1].deleteRecord(rid);
				recordDeleted = true;
			}
			}
			else if(operator.equalsIgnoreCase(">"))
			{
			if(t1.getIntFld( 1)>Integer.parseInt(value))
			{
				if(matchfound == false)
					matchfound= true;
				hf[condn_columnno-1].deleteRecord(rid);
				recordDeleted = true;
			}
			}
			else if(operator.equalsIgnoreCase("<"))
			{
			if(t1.getIntFld( 1)< Integer.parseInt(value))
			{
				if(matchfound == false)
					matchfound= true;
				hf[condn_columnno-1].deleteRecord(rid);
				recordDeleted = true;
			}
			}
			}
		//	RID rtemp = new RID();
			for(int n=0;n<this.numcolumns;n++)
			{
				if(n!= (condn_columnno-1))
				{
					if(scan[n].getNext(rid)!= null)
					{
						if(	recordDeleted == true)
						{
							hf[n].deleteRecord(rid);
						}
					}
				}
			}
		
		}
		if(matchfound == false)
					System.out.println("No matching record were found for given value");
		}
		}
		catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			try {
				// IntegerValue vc = new IntegerValue(new Integer(1));
				// cf.createBitMapIndex(2, (ValueClass)vc);
				// for(i=0;i<this.tidArr.length;i++)
				// cf.getTuple(this.tidArr[i]);
				// cf.markTupleDeleted(tid);
				// cf.purgeAllDeletedTuples();
				SystemDefs.JavabaseBM.unpinAllPages();
				SystemDefs.JavabaseBM.flushAllPages();
				System.out.println("Number of Pages Read: " + PCounter.rcounter);
				System.out.println("Number of Pages Written: "
						+ PCounter.wcounter);
			} catch (Exception e) {
			}
		}


	} 
	
	
	public static void main(String args[]) throws IOException, HFException,
			HFBufMgrException, HFDiskMgrException {
	

		
		String dbpath =  "cdbname";
		String targetColumn="", targetValue= "", operation="";
		//String dbpath = "/tmp/"+System.getProperty("user.name")+".minibase.jointestdb";
		Scanner sc = new Scanner(System.in);
		 System.out.println("Enter Constraint Column Name");
		 targetColumn =sc.next();
		 System.out.println("Enter the operation needed ");
		 operation=sc.next();
		 System.out.println("Enter Constraint value ");
		 targetValue=sc.next();
		 System.out.println("Enter the buffer pool size");
		   int numbuf = sc.nextInt();
//		 targettemp=sc.next();
//		 valcons=sc.next();
//		 numbuf = sc.nextInt();
		 
//		 accesstype = sc.next();
		 
		//String cdbname = "cdbname";
		DeleteQueryTest qu = new DeleteQueryTest();
		// System.out.println("enter the number of target columns");
		// targetnum=sc.nextInt();
		String[] target = new String[1];
		target[0] = "C";
		//qu.runtestdelete(dbpath,"hpfile", "C", target, "=", "1", "delete");
		qu.runTest1(dbpath,"hpfile", targetColumn, target, operation, targetValue, "filescan",numbuf);

	}
}